package edu.uic.ids517.servlet;

import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import edu.uic.ids517.model.DatabaseAccessBean;
import edu.uic.ids517.model.UserLoginBean;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("LoginServlet");
		String successUrl = "/mainMenu.jsp";
		String failureUrl = "/Error.jsp";
		HttpSession session = request.getSession();

		/***   UserLoginBean  ****/
		UserLoginBean userInfo = (UserLoginBean) session.getAttribute("userLoginBean");
		userInfo.setUserName(request.getParameter("userName"));

		//password encryption
		String plaintextPassword = request.getParameter("password");
		MessageDigest m;
		String hashtext = "password";
		try {
			m = MessageDigest.getInstance("MD5");
			m.reset();
			m.update(plaintextPassword.getBytes());
			byte[] digest = m.digest();
			BigInteger bigInt = new BigInteger(1,digest);
			hashtext = bigInt.toString(16);
		} catch (NoSuchAlgorithmException e) {
			System.out.println("Encryption Failed");
			e.printStackTrace();
		}

		userInfo.setPassword(hashtext);
		//userInfo.setPassword(request.getParameter("password"));

		/***   DbLoginBean  ****/
		DatabaseAccessBean dbase = (DatabaseAccessBean) session.getAttribute("dbaseBean"); 
		dbase.setUserLoginBean(userInfo); 
		
		dbase.connect();

		String type = "";

		type = dbase.validateUser();


		System.out.println("type is " + type);
		if(!("invalid".equals(type))){
			System.out.println("Login Successful. Type is "+ type);
			System.out.println(successUrl);
			
			session.setAttribute("userType", type);
			
			dbase.insertTimestamp(userInfo.getUserName()); 	

			RequestDispatcher dispatcher = request.getRequestDispatcher(successUrl); 
			dispatcher.forward(request, response); 
		}
		else{
			RequestDispatcher dispatcher = request.getRequestDispatcher(failureUrl);
			request.setAttribute("errorMessage", "User Login Failure: Invalid username/password!");
			dispatcher.forward(request, response);
		}

	}

}
